import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:magma/heartbeat/helpers/magma_tap.dart';
import 'package:qlevar_router/qlevar_router.dart';
import 'package:stacked/stacked.dart';
import '../../heartbeat/helpers/magma_constant.dart';
import '../../heartbeat/helpers/magma_text_style.dart';
import '../../heartbeat/helpers/magma_color.dart';
import '../../heartbeat/helpers/magma_router.dart';
import '../../heartbeat/helpers/magma_url.dart';
import '../../heartbeat/helpers/magma_toast.dart';
import '../../comms_link/app_state.dart';

/// 设置页面控制器
class ConfigPanelHandler extends BaseViewModel {
  /// 打开隐私政策
  Future<void> launchPrivacyPolicy() async {
    try {
      await MagmaUrl.openUrl(MagmaConstant.privacyPolicyUrl);
    } catch (e) {
      setError('Failed to open Privacy Policy');
    }
  }

  /// 打开服务条款
  Future<void> launchTermsOfService() async {
    try {
      await MagmaUrl.openUrl(MagmaConstant.termsOfServiceUrl);
    } catch (e) {
      setError('Failed to open Terms Of Service');
    }
  }

  /// 打开用户协议
  Future<void> launchEula() async {
    try {
      await MagmaUrl.openUrl(MagmaConstant.eulaUrl);
    } catch (e) {
      setError('Failed to open EULA');
    }
  }

  /// 执行退出登录
  void performLogout() {
    appState.userStore.logoutUser();
  }
}

/// 设置页面
class SetupStory extends StatefulWidget {
  const SetupStory({super.key});

  @override
  State<SetupStory> createState() => _SetupStoryState();
}

class _SetupStoryState extends State<SetupStory> {
  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<ConfigPanelHandler>.reactive(
      viewModelBuilder: () => ConfigPanelHandler(),
      builder: (context, viewModel, child) {
        return Scaffold(
          backgroundColor: MagmaColor.black,
          body: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(MagmaConstant.background),
                fit: BoxFit.cover,
              ),
            ),
            child: SafeArea(
              child: Column(
                children: [
                  // 标题栏
                  _renderTopBar(),

                  SizedBox(height: 2.h),

                  // 设置选项列表
                  Expanded(
                    child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 16.w),
                      child: Column(
                        children: [
                          // Privacy Policy
                          _renderSettingOption(
                            title: 'Privacy Policy',
                            onTap: () => viewModel.launchPrivacyPolicy(),
                          ),

                          SizedBox(height: 16.h),

                          // Terms Of Service
                          _renderSettingOption(
                            title: 'Terms Of Service',
                            onTap: () => viewModel.launchTermsOfService(),
                          ),

                          SizedBox(height: 16.h),

                          // Eula
                          _renderSettingOption(
                            title: 'Eula',
                            onTap: () => viewModel.launchEula(),
                          ),

                          SizedBox(height: 16.h),

                          // Delete account
                          _renderSettingOption(
                            title: 'Delete account',
                            onTap:
                                () => _displayDeleteAccountConfirmation(
                                  viewModel,
                                ),
                          ),

                          Spacer(),

                          // Log Out 按钮
                          _renderLogoutButton(viewModel),

                          SizedBox(height: 40.h),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  /// 渲染顶部栏
  Widget _renderTopBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      child: Row(
        children: [
          // 返回按钮
          MagmaTap(
            onTap: () => QR.back(),
            child: Image.asset(
              MagmaConstant.back,
              width: 20.w,
              height: 20.w,
              color: MagmaColor.white,
            ),
          ),

          // 标题
          Expanded(
            child: Center(
              child: Text('set up').blackHanSans(
                fontSize: 24.sp,
                color: MagmaColor.white,
                fontWeight: FontWeight.w400,
              ),
            ),
          ),

          // 占位，保持标题居中
          SizedBox(width: 20.w),
        ],
      ),
    );
  }

  /// 渲染设置选项
  Widget _renderSettingOption({
    required String title,
    required VoidCallback onTap,
  }) {
    return MagmaTap(
      onTap: onTap,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 0.w, vertical: 6.h),

        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(title).inter(
              fontSize: 16.sp,
              color: MagmaColor.white,
              fontWeight: FontWeight.w400,
            ),
            Icon(Icons.chevron_right, color: MagmaColor.white, size: 24.w),
          ],
        ),
      ),
    );
  }

  /// 渲染退出登录按钮
  Widget _renderLogoutButton(ConfigPanelHandler viewModel) {
    return MagmaTap(
      onTap: () => _handleLogoutAction(viewModel),
      child: Container(
        width: double.infinity,
        height: 56.h,
        decoration: BoxDecoration(
          color: MagmaColor.purple,
          borderRadius: BorderRadius.circular(28.r),
        ),
        child: Center(
          child: Text('Log Out').blackHanSans(
            fontSize: 20.sp,
            color: MagmaColor.black,
            fontWeight: FontWeight.w400,
          ),
        ),
      ),
    );
  }

  /// 显示删除账号确认对话框
  void _displayDeleteAccountConfirmation(ConfigPanelHandler viewModel) {
    showDialog(
      context: context,
      barrierColor: Colors.black.withOpacity(0.7),
      builder: (context) {
        return Dialog(
          backgroundColor: Colors.transparent,
          child: Container(
            padding: EdgeInsets.all(24.w),
            decoration: BoxDecoration(
              color: MagmaColor.black,
              borderRadius: BorderRadius.circular(12.r),
              border: Border.all(
                color: MagmaColor.white.withOpacity(0.3),
                width: 1.w,
              ),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 标题
                Text('Delete Account').blackHanSans(
                  fontSize: 20.sp,
                  color: MagmaColor.white,
                  fontWeight: FontWeight.w700,
                ),

                SizedBox(height: 16.h),

                // 提示文本
                Text(
                  'Are you sure you want to delete your account? This action cannot be undone.',
                  textAlign: TextAlign.center,
                ).inter(
                  fontSize: 14.sp,
                  color: MagmaColor.white.withOpacity(0.8),
                  fontWeight: FontWeight.w400,
                ),

                SizedBox(height: 24.h),

                // 按钮行
                Row(
                  children: [
                    // 取消按钮
                    Expanded(
                      child: MagmaTap(
                        onTap: () => Navigator.of(context).pop(),
                        child: Container(
                          height: 44.h,
                          decoration: BoxDecoration(
                            color: MagmaColor.grey.withOpacity(0.3),
                            borderRadius: BorderRadius.circular(22.r),
                            border: Border.all(
                              color: MagmaColor.white.withOpacity(0.5),
                              width: 1.w,
                            ),
                          ),
                          child: Center(
                            child: Text('Cancel').blackHanSans(
                              fontSize: 16.sp,
                              color: MagmaColor.white,
                              fontWeight: FontWeight.w400,
                            ),
                          ),
                        ),
                      ),
                    ),

                    SizedBox(width: 12.w),

                    // 确认按钮
                    Expanded(
                      child: MagmaTap(
                        onTap: () {
                          Navigator.of(context).pop();
                          _executeAccountDeletion(viewModel);
                        },
                        child: Container(
                          height: 44.h,
                          decoration: BoxDecoration(
                            color: Colors.red,
                            borderRadius: BorderRadius.circular(22.r),
                          ),
                          child: Center(
                            child: Text('Delete').blackHanSans(
                              fontSize: 16.sp,
                              color: MagmaColor.white,
                              fontWeight: FontWeight.w400,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 执行账号删除（实际为退出登录）
  void _executeAccountDeletion(ConfigPanelHandler viewModel) {
    // 执行退出登录
    viewModel.performLogout();

    // 显示成功提示
    MagmaToast.success(context, title: 'Account deleted successfully');

    // 延迟一下再跳转，让用户看到提示
    Future.delayed(const Duration(milliseconds: 500), () {
      // 跳转到主页
      QR.to(MagmaRouter.mainPath);
    });
  }

  /// 处理退出登录操作
  void _handleLogoutAction(ConfigPanelHandler viewModel) {
    // 执行退出登录
    viewModel.performLogout();

    // 显示成功提示
    MagmaToast.success(context, title: 'Logged out successfully');

    // 延迟一下再跳转，让用户看到提示
    Future.delayed(const Duration(milliseconds: 500), () {
      // 跳转到主页
      QR.to(MagmaRouter.mainPath);
    });
  }
}
